import datetime
import os
import random
import subprocess
import time
import traceback

import numpy
import requests
from loguru import logger
from playwright.sync_api import sync_playwright
import single_login


class ChenFeng:
    def __init__(self, playwright, host, command):
        self.playwright = playwright
        self.host = host
        self.command = command
        self.login_func = single_login.Login(playwright, host, command)
        self.download_path = os.path.join(os.getcwd(), "download")
        if not os.path.exists(self.download_path):
            os.mkdir(self.download_path)
        self.download_path = os.path.join(self.download_path, "bill")
        if not os.path.exists(self.download_path):
            os.mkdir(self.download_path)

    def download_file(self):
        for i in range(20):
            try:
                logger.info('【{}】秒【20】秒'.format(i + 1))
                time.sleep(1)
                if self.login_func.page.query_selector('ul.nav-menu-list >> li:has-text("更多")') is not None and \
                        self.login_func.page.query_selector('ul.nav-menu-list >> li:has-text("更多")').is_visible():
                    logger.info("页面加载完成...")
                    break
            except:
                logger.info(traceback.format_exc())
        # 点击更多
        self.login_func.page.query_selector('ul.nav-menu-list >> li:has-text("更多")').click()
        time.sleep(0.5)
        self.login_func.page.query_selector('ul.nav-more >> li:has-text("资金")').click()
        self.wait(self.login_func.page)
        # 点击对账单确认与查询
        self.login_func.page.query_selector('a:has-text("对账单确认与查询")').click()
        self.wait(self.login_func.page)
        # 关闭调查问卷弹窗
        logger.info('等待20秒页面加载完成...')
        for i in range(20):
            logger.info('【{}】秒【20】秒'.format(i + 1))
            time.sleep(1)
            logger.info("检查是否弹窗遮住了按钮...")
            if self.login_func.page.query_selector('//div[contains(@class, "aes-survey-page--close")]') is not None and \
                    self.login_func.page.query_selector('//div[contains(@class, "aes-survey-page--close")]').is_visible():
                logger.info("弹窗遮住了按钮...")
                self.login_func.page.query_selector('//div[contains(@class, "aes-survey-page--close")]').click()
        frame = None
        for k in range(10):
            # 先调用一下，否则会找不到
            self.login_func.page.query_selector('//*[@id="header"]/div/div/div[3]/div/div[5]')
            frame = self.login_func.page.frame(url='https://web.txcs.tmall.com/pages/chaoshi/settlement_confirm_query_list?*')
            if frame is not None:
                break
            time.sleep(1)
        # 点击明细查询
        if frame is None:
            logger.info('点击【对账单确认与查询】菜单失败')
        self.wait(frame)
        time.sleep(2)
        # 修改日期
        yesterday = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
        frame.query_selector('input[placeholder="起始日期"]').click()
        time.sleep(0.5)
        frame.query_selector('span.next-range-picker-panel-input-start-date >> input').fill(yesterday)
        time.sleep(0.5)
        frame.query_selector('span.next-range-picker-panel-input-end-date >> input').fill(yesterday)
        time.sleep(0.5)
        frame.query_selector('div.next-date-picker-panel-footer >> button').click()
        # 获取供应商下拉数据
        frame.query_selector(
            'div.next-form-item-control >> div.next-form-item:has(label:has-text("供应商")) >> input').click()
        time.sleep(0.5)
        li_list = frame.query_selector_all('ul >> li')[1:]
        for li in li_list:
            if li is None or not li.text_content().startswith("深圳"):
                continue
            logger.info(f"正在查询【{li.get_attribute('title')}】的账单数据")
            li.click()
            time.sleep(0.5)
            with self.login_func.page.expect_response(
                    'https://wdksettlement.hemaos.com/statementBill/v3/listForSupplier?*') as res:
                frame.query_selector(
                    'div.ascp-river-query-form__senior-area >> button[type="submit"]:has-text("查询")').click()
            response = res.value
            total = 0
            if response.status == 200:
                total = response.json()['data']['totalCount']
                logger.info(f"共【{total}】条数据")
            if total == 0:
                frame.query_selector(
                    'div.next-form-item-control >> div.next-form-item:has(label:has-text("供应商")) >> input').click()
                continue
            pages = int(total / 20)
            # 先处理第一页
            self.handle_download(frame)
            for page in range(pages):
                # 点击下一页
                with self.login_func.page.expect_response(
                        'https://wdksettlement.hemaos.com/statementBill/v3/listForSupplier?*') as res:
                    frame.query_selector('button.next-next').click()
                response = res.value
                self.handle_download(frame)
            frame.query_selector(
                'div.next-form-item-control >> div.next-form-item:has(label:has-text("供应商")) >> input').click()

    def handle_download(self, frame):
        tr_list = frame.query_selector_all('div.next-table-lock-right >> div.next-table-body >> table >> tr')
        for tr in tr_list:
            tr.query_selector('a:has-text("明细导出")').click()
            self.wait(self.login_func.page)
            time.sleep(2)
            if frame.query_selector('div[role="dialog"]') is not None:
                content = frame.query_selector('div[role="dialog"] >> div.content').text_content()
                logger.info(content)
                frame.query_selector('div[role="dialog"] >> button:has-text("知道了")').click()
                time.sleep(2)
                continue
            download_frame = None
            for k in range(5):
                try:
                    self.login_func.page.query_selector('div')
                    download_frame = self.login_func.page.frame(
                        url='https://web.txcs.tmall.com/river/app/settlement_download/entities/DownloadFile/query?*')
                    if download_frame is not None:
                        break
                    time.sleep(1)
                except:
                    pass
            if download_frame is None:
                raise Exception('点击【明细导出】失败')
            # 等待下载
            for j in range(30):
                try:
                    if download_frame.query_selector(
                            'div.next-table-body >> table >> tr >> nth=0 >> td >> span:has-text("下载"):visible') is None and download_frame.query_selector(
                        'button:has(i.next-icon-turnleft)') is not None and download_frame.query_selector(
                        'button:has(i.next-icon-turnleft)').is_visible():
                        logger.info("点击刷新按钮...")
                        download_frame.query_selector('button:has(i.next-icon-turnleft)').click()
                        time.sleep(2)
                    if download_frame.query_selector('div.next-table-body >> table >> tr >> nth=0 >> td >> span:has-text("下载"):visible') is not None:
                        break
                except:
                    traceback.print_exc()
            with self.login_func.page.expect_download() as download_info:
                download_frame.query_selector(
                    'div.next-table-body >> table >> tr >> nth=0 >> td >> span:has-text("下载"):visible').click()
            download_obj = download_info.value
            file_path = os.path.join(self.download_path, download_frame.query_selector(
                'div.next-table-body >> table >> tr >> td >> nth=1').text_content())
            # 删除旧文件
            if os.path.exists(file_path):
                os.remove(file_path)
            download_obj.save_as(file_path)
            # 等待文件下载完成
            for i in range(60):
                if os.path.exists(file_path):
                    break
                time.sleep(1)
            if not os.path.exists(file_path):
                raise Exception(f"【{file_path}】下载失败")
            logger.info(f"【{file_path}】下载成功")
            # 上传文件
            self.upload_file(file_path)
            # 关闭标签
            self.login_func.page.query_selector_all('span[title="关闭"]')[-1].click()
            time.sleep(0.5)

    def run(self):
        self.login_func.login()
        self.download_file()
        os.system('taskkill /F /IM chrome.exe')

    def upload_file(self, file_path):
        try:
            url = self.host + "/bill/sysBillImport"
            logger.info("正在上传文件到服务器：" + url)
            files = [
                ('file', (open(file_path, 'rb')))
            ]
            response = requests.request("POST", url, files=files)
            print(response.text)
        except:
            traceback.print_exc()

    def wait(self, page, seconds=1):
        page.wait_for_load_state(state="domcontentloaded")
        time.sleep(seconds)

    def close(self):
        try:
            if self.login_func.page:
                self.login_func.page.close()
        except:
            pass
        try:
            if self.login_func.browser:
                self.login_func.browser.close()
        except:
            pass
        try:
            if self.login_func.context:
                self.login_func.context.close()
        except:
            pass


def main(host, command):
    for i in range(6):
        try:
            with sync_playwright() as playwright:
                chen_feng = ChenFeng(playwright, host, command)
                chen_feng.run()
                chen_feng.close()
            return True
        except:
            logger.info(traceback.format_exc())
    return False
